package cn.itsource.hrm.userdetails;

import cn.itsource.hrm.domain.LoginUser;
import cn.itsource.hrm.domain.Permission;
import cn.itsource.hrm.exception.Assert;
import cn.itsource.hrm.mapper.PermissionMapper;
import cn.itsource.hrm.service.ILoginUserService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDeatilsServiceImpl implements UserDetailsService {

    @Autowired
    private ILoginUserService loginUserService;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * Security底层会调用该方法来加载数据库中的用户信息
     *
     * @param username : 用户名
     * @return ： 把用户信息封装成UserDetails返回
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.根据用户名查询Login
        Assert.assertNotEmpty(username,"用户名不可为空");
        Wrapper<LoginUser> warpper = new EntityWrapper<>();
        warpper.eq("username" , username);
        LoginUser loginUser = loginUserService.selectOne(warpper);
        if(loginUser == null)throw new UsernameNotFoundException("用户没找到");

        //2.查询用户的权限
        List<Permission> permissions = permissionMapper.selectByUserId(loginUser.getId());

        //map:映射
        List<SimpleGrantedAuthority> authorities = permissions.stream()
                        .map(permission -> new SimpleGrantedAuthority(permission.getSn()))
                        .collect(Collectors.toList());

        //如何拿到机构？1.调用Feign 管理中心查询机构  2.冗余一个
        String password = loginUser.getPassword();
        loginUser.setPassword(null);
        String login = JSON.toJSONString(loginUser);

        return new User(
                login,   //用户名 loginUser
                password, //密码
                true, //账号启用
                true, //账户是否过期
                true, //密码是否过期
                true ,//账户是否锁定
                authorities ); //用户的权限
    }
}
